package will.android;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;

public class TimerActivity extends Activity
{
   private Handler mHandler = new Handler(); 
   private int labelNo    = 0;
   private long currTime  = 0L;
   private long mStartTime = 0L;
   TextView mTimeTextField;

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);

       mTimeTextField = (TextView)findViewById(R.id.mTimeLabel);

       Button startButton = (Button)findViewById(R.id.buttonStart);
       Button stopButton = (Button)findViewById(R.id.buttonStop);
       stopButton.setOnClickListener(new View.OnClickListener(){
           
             public void onClick(View v) {
                 mHandler.removeCallbacks(mUpdateTimeTask);
             }
          });
       

       
       startButton.setOnClickListener(new View.OnClickListener() {

           public void onClick(View v) {
                  if (mStartTime == 0L) {
                       mStartTime = System.currentTimeMillis();
                       mHandler.removeCallbacks(mUpdateTimeTask);
                       mHandler.postDelayed(mUpdateTimeTask, 100);
                  }
           }
       });
   }

   private Runnable mUpdateTimeTask = new Runnable()
  {
      public void run() {

          final long start = mStartTime;
          long elapseTime = System.currentTimeMillis() - start;
          int seconds = (int) (elapseTime / 1000);
          int minutes = seconds / 60;
          seconds     = seconds % 60;

          if (seconds < 10) {
              mTimeTextField.setText("" + minutes + ":0" + seconds);
          } else {
              mTimeTextField.setText("" + minutes + ":" + seconds);            
          }

          // add a delay to adjust for computation time
          long delay = (1000 - (elapseTime%1000));

          mHandler.postDelayed(this, delay);
      }
   };
}